import { revokePayableStatementApi } from "@/api/financialManagement/payableManagement/index";
import CommonHook from "@/hook/commonHook";
import { message, Modal } from "ant-design-vue";
import { Ref, computed, createVNode } from "vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import {
  approvalExportDataApi,
  getApprovalListApi,
  getListApi,
  getPageStaticApi,
  passApplyApi,
  preApplyExportDataApi,
  reSubmitApplyApi,
  statisticsDataApi,
  statisticsDataApplyApi,
  withDrawApplyApi
} from "@/api/financialManagement/payableManagement/paymentApproval";
export default function OperationHook(state: {
  searchForm: PaymentApproval.SearchForm;
  tableData: Ref<PaymentApproval.ListRows[]>;
  tableRef: Ref<any>;
  dialogOpts: Base.DialogOpts;
  drawerOpts: Base.DrawerOpts;
  loading: Ref<boolean>;
  activeKey: Ref<string>;
  pageStat: Ref<Base.GeneraDataType>;
}) {
  const { searchForm, tableData, drawerOpts, loading, tableRef, dialogOpts, activeKey, pageStat } = state;
  const selectRows = computed<Array<StatementPayable.ListRows>>(() => {
    return tableRef.value.xTable.getCheckboxRecords() || [];
  });
  const { downloadFileByBlob } = CommonHook();
  const getData = async () => {
    const params: Parameters<typeof getListApi>[0] = {
      ...getParams(),
      statusList: [Number(activeKey.value)]
    };
    loading.value = true;
    tableData.value = [];
    let requestFn;
    if (activeKey.value === "0") {
      requestFn = getListApi;
      Reflect.deleteProperty(params, "statusList");
    } else requestFn = getApprovalListApi;
    return requestFn(params)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          tableData.value = data.records || [];
          searchForm.beforePageNum = searchForm.pageNum;
          searchForm.total = Number(data.total);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  };
  const getParams = () => {
    const { agentIdList, statementType, companyIdList, waybillNum, payableStatementNumber, beforePageNum, pageNum, pageSize } = searchForm;
    const params: any = {
      agentIdList,
      statementType,
      companyIdList,
      beforePageNum,
      pageNum,
      pageSize
    };
    if (waybillNum)
      params.waybillNum = waybillNum
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (payableStatementNumber)
      params.payableStatementNumber = payableStatementNumber
        .trim()
        .replace(/,{1,}|，{1,}|\+{1,}|\s{1,}/g, ",")
        .split(",");
    if (searchForm.sort) {
      params.order = searchForm.order;
      params.sort = searchForm.sort;
    }
    return params;
  };
  const pageStateic = () => {
    const params = getParams();
    return getPageStaticApi({ ...params }).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        Object.assign(pageStat.value, {
          0: data[0],
          1: data[1],
          2: data[2],
          3: data[3]
        });
        // activeKey.value = String(getNoZeroKey(pageStat.value, ["0", "1", "2", "3"]));
      }
    });
  };
  const searchHandle = async () => {
    searchForm.pageNum = 1;
    await pageStateic();
    getData();
  };
  const changeTabHandle = () => {
    getData();
  };
  // 详情
  const showDetailsHandle = (row: PaymentApproval.ListRows) => {
    drawerOpts.title = `详情`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "Details";
    drawerOpts.passData = row;
    drawerOpts.visible = true;
  };
  // 申请打款
  const applyPaymentHandle = () => {
    if (!selectRows.value.length) return message.error("请先勾选账单号!");
    const allCompany = selectRows.value.map((t: any) => t.companyName || "");
    if (Array.from(new Set(allCompany)).length > 1) return message.error("只能勾选相同公司的账单进行操作!");
    drawerOpts.title = `申请付款`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.passData = selectRows.value;
    drawerOpts.component = "ApplyPayment";
    drawerOpts.visible = true;
  };
  // 查看审批详情
  const showApprovalInfoHandle = (row: PaymentApproval.ListRows) => {
    drawerOpts.title = `申请详情`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.passData = row;
    drawerOpts.component = "ApprovalPending";
    drawerOpts.visible = true;
  };
  // 撤回申请
  const withDrawApplyHandle = (row: PaymentApproval.ListRows) => {
    return withDrawApplyApi(row.id).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("操作成功!");
        searchHandle();
      }
    });
  };
  // 通过申请
  const passApplyHandle = (row: PaymentApproval.ListRows) => {
    Modal.confirm({
      title: "是否通过当前申请?",
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        return passApplyApi([row.id]).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            searchHandle();
          }
        });
      }
    });
  };
  // 批量通过
  const batchPassApplyHandle = () => {
    if (!selectRows.value.length) return message.error("请先勾选审批单号!");
    Modal.confirm({
      title: "是否通过已选申请?",
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        return passApplyApi(selectRows.value.map((t: any) => t.id)).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("操作成功!");
            searchHandle();
          }
        });
      }
    });
  };
  // 驳回申请
  const refuseApplyHandle = (row: PaymentApproval.ListRows) => {
    dialogOpts.title = `驳回申请`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.passData = [row];
    dialogOpts.component = "RejectApply";
    dialogOpts.visible = true;
  };
  // 批量驳回
  const batchRefuseApplyHandle = () => {
    if (!selectRows.value.length) return message.error("请先勾选审批单号!");
    dialogOpts.title = `驳回申请`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.passData = selectRows.value;
    dialogOpts.component = "RejectApply";
    dialogOpts.visible = true;
  };
  // 核销费用
  const writeOffFeeHandle = (row: PaymentApproval.ListRows) => {
    drawerOpts.title = `费用核销`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.passData = [row];
    drawerOpts.component = "WriteOffFee";
    drawerOpts.visible = true;
  };
  // 批量核销费用
  const batchWriteOffFeeHandle = () => {
    if (!selectRows.value.length) return message.error("请先勾选审批单号!");
    drawerOpts.title = `费用核销`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.passData = selectRows.value;
    drawerOpts.component = "WriteOffFee";
    drawerOpts.visible = true;
  };
  // 重新提交
  const reSubmitApplyHandle = (row: PaymentApproval.ListRows) => {
    reSubmitApplyApi([row.id]).then((res: any) => {
      const { code } = res;
      if (code === 200) {
        message.success("提交成功!");
        searchHandle();
      }
    });
  };
  // 导出
  const downloadDataHandle = () => {
    const params = {
      ...getParams(),
      statusList: [Number(activeKey.value)],
      idList: selectRows.value.map((t: any) => t.id)
    };
    let requestFn;
    if (activeKey.value === "0") {
      requestFn = preApplyExportDataApi;
      Reflect.deleteProperty(params, "statusList");
    } else requestFn = approvalExportDataApi;
    loading.value = true;
    return requestFn(params)
      .then((res: any) => {
        downloadFileByBlob(res, activeKey.value === "1" ? "待申请应付账单.xlsx" : "应付账单.xlsx");
        message.success("下载成功!");
      })
      .finally(() => (loading.value = false));
  };
  // 导入对账单
  const importStatementHandle = () => {
    dialogOpts.title = `导入对账单`;
    dialogOpts.width = "520px";
    dialogOpts.type = 1;
    dialogOpts.component = "ImportStatement";
    dialogOpts.visible = true;
  };
  // 导入 加收单
  const importAddFeeHandle = () => {
    dialogOpts.title = `导入加收单`;
    dialogOpts.width = "520px";
    dialogOpts.type = 2;
    dialogOpts.component = "ImportStatement";
    dialogOpts.visible = true;
  };

  // 撤销账单
  const reverseBillHandle = (row: StatementPayable.ListRows) => {
    Modal.confirm({
      title: "是否撤销当前账单?",
      icon: createVNode(ExclamationCircleOutlined),
      onOk() {
        revokePayableStatementApi(row.id).then((res: any) => {
          const { code } = res;
          if (code === 200) {
            message.success("撤销成功!");
            searchHandle();
          }
        });
      }
    });
  };
  // 待接收账单
  const showPreAcceptedBillHandle = () => {
    drawerOpts.title = `待接收账单`;
    drawerOpts.width = "1200px";
    drawerOpts.type = 1;
    drawerOpts.component = "PreAcceptedBill";
    drawerOpts.visible = true;
  };
  // 获取统计数据
  const getStatisticsDataFn = () => {
    const params: any = {
      ...getParams(),
      statusList: [Number(activeKey.value)]
    };
    let requestFn;
    if (activeKey.value === "0") {
      requestFn = statisticsDataApi;
      Reflect.deleteProperty(params, "statusList");
    } else requestFn = statisticsDataApplyApi;
    if (selectRows.value.length) params.idList = selectRows.value.map((t: PaymentApproval.ListRows) => t.id);
    return requestFn(params).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        dialogOpts.passData = data || {};
      }
    });
  };
  // 查看统计
  const showStatictisHandle = () => {
    dialogOpts.title = "查看统计";
    dialogOpts.width = "720px";
    dialogOpts.component = "DataStatistics";
    dialogOpts.visible = true;
  };
  return {
    searchHandle,
    getData,
    showDetailsHandle,
    importStatementHandle,
    importAddFeeHandle,
    changeTabHandle,
    downloadDataHandle,
    reverseBillHandle,
    selectRows,
    showPreAcceptedBillHandle,
    applyPaymentHandle,
    showApprovalInfoHandle,
    withDrawApplyHandle,
    passApplyHandle,
    batchPassApplyHandle,
    refuseApplyHandle,
    batchRefuseApplyHandle,
    writeOffFeeHandle,
    batchWriteOffFeeHandle,
    reSubmitApplyHandle,
    getStatisticsDataFn,
    showStatictisHandle
  };
}
